<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<link rel="stylesheet" type="text/css" href="../../elementui/elementui.css" />
	<style>
		html,body,#app {
			height: 100%;
		}
		body {
			margin: 0;
		}
		.chat-form {
			height: 100%;
			display: flex;
			flex-direction: column;
		}
		.merchant-selector {
			padding: 10px 12px;
			border-bottom: 1px solid #eeeeee;
			background-color: #f5f5f5;
		}
		.chat-content {
			overflow-y: scroll;
			border: 1px solid #eeeeee;
			margin: 0;
			padding: 0;
			width: 100%;
			flex: 1;
		}
		.left-content {
			float: left;
			margin-bottom: 10px;
			padding: 10px;
		}
		.right-content {
			float: right;
			margin-bottom: 10px;
			padding: 10px;
		}
		.clear-float {
			clear: both;
		}
		.btn-input {
			margin-left: 0px;
			display: flex;
			width: 100%;
			padding: 10px 12px;
			box-sizing: border-box;
		}
		.chat-header {
			display: flex;
			align-items: center;
			gap: 10px;
		}
		.user-info {
			font-size: 14px;
			color: #666;
		}
	</style>
</head>
<body style="overflow-y: hidden;overflow-x: hidden;">
<div id="app">
	<el-form class="detail-form-content chat-form" ref="ruleForm" label-width="0">
		<!-- 商家选择区域 -->
		<div class="merchant-selector">
			<div class="chat-header">
				<el-select
						v-model="selectedMerchant"
						placeholder="请选择要对话的商家"
						@change="onMerchantChange"
						style="width: 300px;">
					<el-option
							v-for="merchant in merchantList"
							:key="merchant.id"
							:label="merchant.name"
							:value="merchant.id">
					</el-option>
				</el-select>
				<div class="user-info" v-if="currentUser.username">
					当前用户: {{ currentUser.username }}
				</div>
				<div class="user-info" v-if="selectedMerchantName">
					对话商家: {{ selectedMerchantName }}
				</div>
			</div>
		</div>

		<!-- 聊天内容区域 -->
		<div class="chat-content" ref="chatContent">
			<div v-if="!selectedMerchant" style="text-align: center; padding: 50px; color: #999;">
				请先选择要对话的商家
			</div>
			<div v-else>
				<div v-bind:key="item.id" v-for="item in dataList">
					<div v-if="item.ask" class="left-content">
						<el-alert class="text-content" :title="item.ask" :closable="false" type="success"></el-alert>
					</div>
					<div v-else class="right-content">
						<el-alert class="text-content" :title="item.reply" :closable="false" type="warning"></el-alert>
					</div>
					<div class="clear-float"></div>
				</div>
			</div>
		</div>

		<!-- 输入区域 -->
		<div class="btn-input">
			<el-input
					style="flex: 1;margin-right: 10px;"
					v-model="ruleForm.ask"
					placeholder="Please enter your message content."
					clearable
					:disabled="!selectedMerchant"
					@keyup.enter.native="onSubmit">
			</el-input>
			<el-button
					type="primary"
					@click="onSubmit"
					:disabled="!selectedMerchant">
				Send
			</el-button>
		</div>
	</el-form>
</div>

<!-- layui -->
<script src="../../layui/layui.js"></script>
<!-- vue -->
<script src="../../js/vue.js"></script>
<!-- elementui -->
<script src="../../elementui/elementui.js"></script>
<!-- 组件配置信息 -->
<script src="../../js/config.js"></script>
<!-- 扩展插件配置信息 -->
<script src="../../modules/config.js"></script>
<!-- 工具方法 -->
<script src="../../js/utils.js"></script>
<script type="text/javascript">
	var app = new Vue({
		el: "#app",
		data() {
			return {
				id: "",
				ruleForm: {},
				dataList: [],
				inter: null,
				merchantList: [],        // 商家列表
				selectedMerchant: '',    // 选中的商家ID
				selectedMerchantName: '', // 选中的商家名称
				currentUser: {           // 当前用户信息
					id: '',
					username: ''
				}
			}
		},
		methods: {
			// 初始化
			init(id) {
				this.id = id;
				this.getCurrentUser();
				this.getMerchantList();

				// 如果之前选择过商家，恢复选择状态
				var savedMerchant = localStorage.getItem('selectedMerchant');
				if (savedMerchant) {
					this.selectedMerchant = savedMerchant;
					this.getList();
					this.startAutoRefresh();
				}
			},

			// 获取当前用户信息
			getCurrentUser() {
				var userId = localStorage.getItem('userid');
				var username = localStorage.getItem('username');

				this.currentUser = {
					id: userId,
					username: username || '用户' + userId
				};

				// 如果没有username，可以调用接口获取
				if (!username && userId) {
					layui.http.request('user/info', 'get', {
						id: userId
					}, (res) => {
						if (res.data && res.data.username) {
							this.currentUser.username = res.data.username;
							localStorage.setItem('username', res.data.username);
						}
					});
				}
			},

			// 获取商家列表
			getMerchantList() {
				layui.http.request('users/list', 'get', {}, (res) => {
					this.merchantList = res.data.list || [];
				});
			},

			// 商家选择改变
			onMerchantChange(merchantId) {
				if (merchantId) {
					// 找到选中商家的名称
					var merchant = this.merchantList.find(m => m.id === merchantId);
					this.selectedMerchantName = merchant ? merchant.name : '';

					// 保存选择到本地存储
					localStorage.setItem('selectedMerchant', merchantId);
					localStorage.setItem('selectedMerchantName', this.selectedMerchantName);

					// 清空之前的对话数据
					this.dataList = [];

					// 获取与该商家的对话记录
					this.getList();
					this.startAutoRefresh();
				} else {
					this.selectedMerchantName = '';
					this.dataList = [];
					this.stopAutoRefresh();
				}
			},

			// 开始自动刷新
			startAutoRefresh() {
				this.stopAutoRefresh();
				var that = this;
				var inter = setInterval(function() {
					that.getList();
				}, 10000);
				this.inter = inter;
			},

			// 停止自动刷新
			stopAutoRefresh() {
				if (this.inter) {
					clearInterval(this.inter);
					this.inter = null;
				}
			},

			// 获取对话列表
			getList() {
				if (!this.selectedMerchant) return;

				layui.http.request('chat/list', 'get', {
					userid: this.currentUser.id,
					merchantid: this.selectedMerchant,
					sort: 'addtime',
					order: 'asc'
				}, (res) => {
					this.dataList = res.data.list;
					this.$nextTick(() => {
						this.scrollToBottom();
					});
				});
			},

			// 滚动到底部
			scrollToBottom() {
				var chatContent = this.$refs.chatContent;
				if (chatContent) {
					chatContent.scrollTop = chatContent.scrollHeight;
				}
			},

			// 提交消息
			onSubmit() {
				if (!this.selectedMerchant) {
					layer.msg('请先选择要对话的商家', {
						time: 2000,
						icon: 5
					});
					return;
				}

				if (!this.ruleForm.ask || !this.ruleForm.ask.trim()) {
					layer.msg('Please enter your message content.', {
						time: 2000,
						icon: 5
					});
					return;
				}

				// 发送消息到后端，包含用户信息和商家信息
				layui.http.requestJson('chat/add', 'post', {
					userid: this.currentUser.id,
					username: this.currentUser.username,
					merchantid: this.selectedMerchant,
					merchantname: this.selectedMerchantName,
					ask: this.ruleForm.ask.trim()
				}, (res) => {
					this.getList();
					this.ruleForm.ask = "";
				});
			}
		},

		beforeDestroy() {
			this.stopAutoRefresh();
		}
	})

	layui.use(['layer', 'element', 'http', 'jquery'], function() {
		var layer = layui.layer;
		var element = layui.element;
		var http = layui.http;
		var jquery = layui.jquery;
		app.init();
	});
</script>
</body>
</html>